﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls.WebParts;
using System.Security;
using Microsoft.SharePoint.Administration;

namespace IronSharePoint.Web.WebControls
{
    public class IronWebPart : IronBaseWebPart
    {
        [WebBrowsable(false)]
        [Personalizable(PersonalizationScope.Shared)]
        public IronScriptingLanguage ScriptLanguage { get; set; }

        [WebBrowsable(false)]
        [Personalizable(PersonalizationScope.Shared)]
        public string Script { get; set; }

        [WebBrowsable(false)]
        [Personalizable(PersonalizationScope.Shared)]
        public string ScriptSigning { get; set; }

        protected override void OnInit(EventArgs e)
        {
            try
            {
                if (Page.Request["skipIron"] != null && Page.Request["skipIron"] == "true" && SPFarm.Local.CurrentUserIsAdministrator())
                    throw new Exception("skip Iron");

               
                engine = new IronScriptEngine();

                EnsureScriptManager();
                EnsureUpdatePanelFixups();

                if (String.IsNullOrEmpty(Script))
                {
                    if (FeatureId != null && (new Guid(FeatureId)) != Guid.Empty)
                        engine.ScriptResolver.FeatureId = new Guid(FeatureId);
                    engine.CompileScriptFrom(ScriptPath);
                }
                else
                {
                    if (IronScriptSigner.VerifyScriptSigning(Script, ScriptSigning) == false)
                        throw new SecurityException("Invalid script signing!");

                    engine.CompileScript(Script, ScriptLanguage);
                }

                engine.Scope.SetVariable("self", this);

                if (engine.Scope.ContainsVariable("OnInit"))
                {
                    object method = engine.Scope.GetVariable("OnInit");
                    engine.Operations.Call(method, e);
                }
            }
            catch (Exception ex)
            {
                exception = ex;
            }
         
        }

        public override EditorPartCollection CreateEditorParts()
        {
            List<EditorPart> customEditors = new List<EditorPart>();

            IronWebPartEditor ironWPEditor = new IronWebPartEditor();
            ironWPEditor.ID = this.ID + "_editor";
            ironWPEditor.Title = "Iron Settings";
            customEditors.Add(ironWPEditor);

            return new EditorPartCollection(base.CreateEditorParts(), customEditors);
        }
   
    }
}
